package com.petdog.module.user.controller;

import com.petdog.common.dto.ApiResponse;
import com.petdog.common.dto.PageResult;
import com.petdog.common.util.FileUploadUtil;
import com.petdog.infrastructure.entity.Pet;
import com.petdog.infrastructure.entity.User;
import com.petdog.module.pet.service.PetService;
import com.petdog.module.user.service.UserService;
import com.petdog.common.util.UserUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.Principal;
import java.time.LocalDate;
import java.time.format.DateTimeParseException;
import java.util.HashMap;
import java.util.Map;

/**
 * 用户控制器
 * 提供个人中心、个人资料管理等功能
 */
@RestController
@RequestMapping("/api/user")
public class UserController {
    private static final Logger logger = LoggerFactory.getLogger(UserController.class);
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private PetService petService;
    
    @Autowired
    private FileUploadUtil fileUploadUtil;

    /**
     * 获取个人中心概要（用户信息 + 宠物列表摘要）
     * @param principal 当前登录用户
     * @return 个人中心概要信息
     */
    @GetMapping("/profile")
    public ResponseEntity<ApiResponse<Map<String, Object>>> getUserProfile(Principal principal) {
        try {
            // 获取当前登录用户的ID
            Long userId = Long.parseLong(principal.getName());
            
            // 获取用户基本信息
            User user = userService.getUserById(userId);
            if (user == null) {
                logger.warn("用户不存在: {}", userId);
                return new ResponseEntity<>(ApiResponse.error("用户不存在"), HttpStatus.NOT_FOUND);
            }
            
            // 准备响应数据
            Map<String, Object> result = new HashMap<>();
            
            // 构建用户信息
            Map<String, Object> userInfo = new HashMap<>();
            userInfo.put("userId", UserUtils.getUserId(user));
            userInfo.put("nickname", UserUtils.getNickname(user));
            userInfo.put("avatar", fileUploadUtil.getFileAccessUrl(UserUtils.getAvatar(user)));
            userInfo.put("status", UserUtils.getStatus(user));
            
            result.put("userInfo", userInfo);
            
            // 获取用户的宠物列表摘要（最近3个宠物）
            PageResult<Pet> pageResult = petService.getUserPets(userId, 1, 3);
            result.put("petList", pageResult.getList());
            
            return ResponseEntity.ok(ApiResponse.success(result, "获取个人中心概要成功"));
        } catch (Exception e) {
            logger.error("获取个人中心概要失败: {}", e.getMessage());
            return new ResponseEntity<>(ApiResponse.error("系统繁忙，请稍后再试"), HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
    
    /**
     * 获取用户详细信息（用于编辑表单）
     * @param principal 当前登录用户
     * @return 用户详细信息
     */
    @GetMapping("/profile/detail")
    public ResponseEntity<ApiResponse<Map<String, Object>>> getUserProfileDetail(Principal principal) {
        try {
            // 获取当前登录用户的ID
            Long userId = Long.parseLong(principal.getName());
            
            // 获取用户完整信息
            User user = userService.getUserById(userId);
            if (user == null) {
                logger.warn("用户不存在: {}", userId);
                return new ResponseEntity<>(ApiResponse.error("用户不存在"), HttpStatus.NOT_FOUND);
            }
            
            // 检查用户状态
            Integer status = UserUtils.getStatus(user);
            if (status != null && status != 1) {
                logger.warn("账号状态异常，无法获取个人信息: {}, 状态: {}", userId, status);
                return new ResponseEntity<>(ApiResponse.error("账号状态异常，无法获取个人信息"), HttpStatus.FORBIDDEN);
            }
            
            // 准备响应数据
            Map<String, Object> userDetail = new HashMap<>();
            userDetail.put("avatarUrl", fileUploadUtil.getFileAccessUrl(UserUtils.getAvatar(user)));
            userDetail.put("nickname", UserUtils.getNickname(user));
            userDetail.put("gender", UserUtils.getGender(user));
            userDetail.put("birthday", UserUtils.getBirthday(user));
            userDetail.put("email", UserUtils.getEmail(user));
            userDetail.put("phone", UserUtils.getPhone(user));
            userDetail.put("bio", UserUtils.getBio(user));
            userDetail.put("location", UserUtils.getLocation(user));
            
            return ResponseEntity.ok(ApiResponse.success(userDetail, "获取用户详细信息成功"));
        } catch (Exception e) {
            logger.error("获取用户详细信息失败: {}", e.getMessage());
            return new ResponseEntity<>(ApiResponse.error("系统繁忙，请稍后再试"), HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
    
    /**
     * 更新个人信息（支持头像上传）
     * @param principal 当前登录用户
     * @param nickname 昵称
     * @param gender 性别
     * @param birthday 生日
     * @param avatar 头像文件
     * @return 更新结果
     */
    @PutMapping(value = "/profile", consumes = {"multipart/form-data"})
    public ResponseEntity<ApiResponse<Map<String, Object>>> updateUserProfile(
            Principal principal,
            @RequestParam(required = false) String nickname,
            @RequestParam(required = false) Integer gender,
            @RequestParam(required = false) String birthday,
            @RequestPart(required = false) MultipartFile avatar) {
        try {
            // 获取当前登录用户的ID
            Long userId = Long.parseLong(principal.getName());
            
            // 获取用户信息
            User user = userService.getUserById(userId);
            if (user == null) {
                logger.warn("用户不存在: {}", userId);
                return new ResponseEntity<>(ApiResponse.error("用户不存在"), HttpStatus.NOT_FOUND);
            }
            
            // 检查用户状态
            Integer status = UserUtils.getStatus(user);
            if (status != null && status != 1) {
                logger.warn("账号状态异常，无法修改信息: {}, 状态: {}", userId, status);
                return new ResponseEntity<>(ApiResponse.error("账号状态异常，无法修改信息"), HttpStatus.FORBIDDEN);
            }
            
            // 验证并更新昵称
            if (nickname != null && !nickname.isEmpty()) {
                // 验证昵称：1-12字符，限中英文/数字，无特殊符号
                if (!nickname.matches("^[\\u4e00-\\u9fa5a-zA-Z0-9]{1,12}$")) {
                    logger.warn("昵称格式不正确: {}", nickname);
                    return new ResponseEntity<>(ApiResponse.error("昵称格式不正确，应为1-12个中英文或数字字符"), HttpStatus.BAD_REQUEST);
                }
                UserUtils.setNickname(user, nickname);
            }
            
            // 验证并更新性别
            if (gender != null) {
                // 验证性别：0-保密，1-男，2-女
                if (gender < 0 || gender > 2) {
                    logger.warn("性别选择无效: {}", gender);
                    return new ResponseEntity<>(ApiResponse.error("性别选择无效"), HttpStatus.BAD_REQUEST);
                }
                UserUtils.setGender(user, gender);
            }
            
            // 验证并更新生日
            if (birthday != null && !birthday.isEmpty()) {
                try {
                    LocalDate birthDate = LocalDate.parse(birthday);
                    LocalDate now = LocalDate.now();
                    // 验证生日：非未来日期，不超过120年
                    if (birthDate.isAfter(now) || birthDate.isBefore(now.minusYears(120))) {
                        logger.warn("生日无效: {}", birthday);
                        return new ResponseEntity<>(ApiResponse.error("生日无效，请选择120年内的有效日期"), HttpStatus.BAD_REQUEST);
                    }
                    UserUtils.setBirthday(user, birthDate.toString());
                } catch (DateTimeParseException e) {
                    logger.warn("生日格式错误: {}", birthday);
                    return new ResponseEntity<>(ApiResponse.error("生日格式错误，请使用yyyy-MM-dd格式"), HttpStatus.BAD_REQUEST);
                }
            }
            
            // 处理头像上传
            String avatarUrl = null;
            if (avatar != null && !avatar.isEmpty()) {
                try {
                    // 使用FileUploadUtil的uploadAvatar方法处理头像上传
                    String fileName = fileUploadUtil.uploadAvatar(avatar);
                    
                    // 删除旧头像（如果存在且不是默认头像）
                    String oldAvatar = UserUtils.getAvatar(user);
                    if (oldAvatar != null && !oldAvatar.equals("default_avatar.png")) {
                        fileUploadUtil.deleteImage(oldAvatar);
                    }
                    
                    avatarUrl = fileUploadUtil.getFileAccessUrl(fileName);
                    UserUtils.setAvatar(user, fileName);
                } catch (IOException e) {
                    logger.error("头像上传失败: {}", e.getMessage());
                    return new ResponseEntity<>(ApiResponse.error("头像上传失败: " + e.getMessage()), HttpStatus.BAD_REQUEST);
                }
            }
            
            // 更新用户信息
            userService.updateUser(user);
            
            // 准备响应数据
            Map<String, Object> result = new HashMap<>();
            result.put("nickname", UserUtils.getNickname(user));
            result.put("gender", UserUtils.getGender(user));
            result.put("birthday", UserUtils.getBirthday(user));
            if (avatarUrl != null) {
                result.put("avatarUrl", avatarUrl);
            }
            
            return ResponseEntity.ok(ApiResponse.success(result, "更新个人信息成功"));
        } catch (Exception e) {
            logger.error("更新个人信息失败: {}", e.getMessage());
            return new ResponseEntity<>(ApiResponse.error("系统繁忙，请稍后再试"), HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
    
    /**
     * 执行退出登录
     * @param principal 当前登录用户
     * @return 退出结果
     */
    @PostMapping("/logout")
    public ResponseEntity<ApiResponse<Void>> logout(Principal principal) {
        try {
            if (principal != null) {
                Long userId = Long.parseLong(principal.getName());
                logger.info("用户退出登录: {}", userId);
                // 在实际应用中，这里可能需要：
                // 1. 清除用户的Token（如果有Token存储机制）
                // 2. 更新用户的最后退出时间
                // 3. 清理用户的会话信息
            }
            
            // 前端需要清除本地存储的Token并跳转到登录页
            return ResponseEntity.ok(ApiResponse.success(null, "退出登录成功"));
        } catch (Exception e) {
            logger.error("退出登录失败: {}", e.getMessage());
            return new ResponseEntity<>(ApiResponse.error("退出登录失败，请重试"), HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
}
